<template>
  <div class="w-full h-full flex justify-between">
    <div class="menu-aside">
      <game-list-aside @init="handleChange" @change="handleChange" />
    </div>
    <div class="view-main flex justify-between flex-col">
      <div class="px-[15px] py-[15px] flex items-center">
        <el-button type="primary" @click="handleSaveAll(false)" v-if="premsStore.isEditOddsSetting">
          保存设置
        </el-button>
        <el-button type="danger" @click="handleSaveAll(true)" v-if="premsStore.isEditOddsSetting">
          一键设置同类型游戏
        </el-button>
      </div>
      <div class="grow-[1] h-0 mb-[15px] mx-[15px]">
        <el-table
          scrollbar-always-on
          v-loading="state.loading"
          :data="state.list"
          height="100%"
          stripe
          border
          fit
        >
          <el-table-column align="center" prop="BetName" label="玩法">
            <template #default="{ row }: TableItem"> {{ row.Cat2 }}-{{ row.Cat3 }} </template>
          </el-table-column>
          <el-table-column align="center" label="赔率" width="240">
            <template #default="{ row }: TableItem">
              <div class="flex items-center ml-[30px]">
                <el-input-number
                  class="!w-[100px]"
                  size="small"
                  v-model="row.Odds"
                  :min="0"
                  :max="row.MaxOdds"
                  :precision="2"
                  :controls="false"
                />
                <span class="text-[12px] ml-[5px]">&lt;= {{ row.MaxOdds }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="个人单注最低限额" width="240">
            <template #header>
              <div class="flex items-center justify-center">个人单注最低限额</div>
              <div class="flex items-center ml-[30px]">
                <el-input-number
                  class="!w-[100px]"
                  v-model="state.min"
                  size="small"
                  :min="state.minLimit"
                  :max="state.maxLimit"
                  :precision="2"
                  :controls="false"
                  @change="handleMaster"
                />
                <span class="text-[12px] font-normal text-left ml-[5px]">
                  &gt;= {{ state.minLimit }}
                </span>
              </div>
            </template>
            <template #default="{ row }: TableItem">
              <div class="flex items-center ml-[30px]">
                <el-input-number
                  class="!w-[100px]"
                  size="small"
                  :min="row.MinPersonl"
                  :max="row.MaxMaxPreBet"
                  v-model="row.RoomSingleMinLimit"
                  :precision="2"
                  :controls="false"
                />
                <span class="text-[12px] ml-[5px] text-left"> &gt;= {{ row.MinPersonl }} </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="个人单注最高限额" width="240">
            <template #header>
              <div class="flex items-center justify-center">个人单注最高限额</div>
              <div class="flex items-center ml-[20px]">
                <el-input-number
                  class="!w-[100px]"
                  v-model="state.max"
                  size="small"
                  :min="0"
                  :max="state.maxLimit"
                  :precision="2"
                  :controls="false"
                />
                <span class="text-[12px] font-normal text-left ml-[5px]">
                  &lt;= {{ state.maxLimit }}
                </span>
              </div>
            </template>
            <template #default="{ row }: TableItem">
              <div class="flex items-center ml-[20px]">
                <el-input-number
                  class="!w-[100px]"
                  size="small"
                  :min="0"
                  :max="row.MaxMaxPreBet"
                  v-model="row.RoomSingleMaxLimit"
                  :precision="2"
                  :controls="false"
                />
                <span class="text-[12px] ml-[5px] text-left"> &lt;= {{ row.MaxMaxPreBet }} </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="个人单期最高限额" width="240">
            <template #header>
              <div class="flex items-center justify-center">个人单期最高限额</div>
              <div class="flex items-center ml-[20px]">
                <el-input-number
                  class="!w-[100px]"
                  v-model="state.persionMax"
                  size="small"
                  :min="0"
                  :max="state.persionMaxLimit"
                  :precision="2"
                  :controls="false"
                />
                <span class="text-[12px] font-normal text-left ml-[5px]">
                  &lt;= {{ state.persionMaxLimit }}
                </span>
              </div>
            </template>
            <template #default="{ row }: TableItem">
              <div class="flex items-center ml-[20px]">
                <el-input-number
                  class="!w-[100px]"
                  size="small"
                  :min="0"
                  :max="row.MaxMaxSingleBitch"
                  v-model="row.MaxLimitPersonBet"
                  :precision="2"
                  :controls="false"
                />
                <span class="text-[12px] ml-[5px] text-left">
                  &lt;= {{ row.MaxMaxSingleBitch }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单期总限额" width="240">
            <template #header>
              <div class="flex items-center justify-center">单期总限额</div>
              <div class="flex items-center ml-[20px]">
                <el-input-number
                  class="!w-[100px]"
                  v-model="state.all"
                  size="small"
                  :min="0"
                  :max="state.allLimit"
                  :precision="2"
                  :controls="false"
                />
                <span class="text-[12px] font-normal text-left ml-[5px]">
                  &lt;= {{ state.allLimit }}
                </span>
              </div>
            </template>
            <template #default="{ row }: TableItem">
              <div class="flex items-center ml-[20px]">
                <el-input-number
                  class="!w-[100px]"
                  size="small"
                  :min="0"
                  :max="row.MaxMaxBitch"
                  v-model="row.RoomAllLimit"
                  :precision="2"
                  :controls="false"
                />
                <span class="text-[12px] text-left ml-[5px]"> &lt;= {{ row.MaxMaxBitch }} </span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { cloneDeep, isEqual } from "lodash-es";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { reqGameOddsEdit, reqGameOddsShow } from "@/api/odds";
import { usePremsStore } from "@/store/modules/prems";

interface TableItem {
  row: OddsSettingItem;
}

interface State {
  loading: boolean;
  msgGameInfoId: number;
  list: OddsSettingItem[];
  defaultList: OddsSettingItem[];
  odds: number | null;
  min: number | null;
  minLimit: number;
  max: number | null;
  maxLimit: number;
  persionMax: number | null;
  persionMaxLimit: number;
  all: number | null;
  allLimit: number;
}

const premsStore = usePremsStore();
const currentData = ref<GameLeftMo | null>(null);
const state = reactive<State>({
  loading: false,
  msgGameInfoId: 0,
  list: [],
  defaultList: [],
  odds: <number | null>null,
  min: <number | null>null,
  minLimit: 0,
  max: <number | null>null,
  maxLimit: 0,
  persionMax: <number | null>null,
  persionMaxLimit: 0,
  all: <number | null>null,
  allLimit: 0
});

// 比较原始数据和修改后的数据，找出有变化的对象
const getChangedItems = (original: OddsSettingItem[], modified: OddsSettingItem[]) => {
  const changedItems: OddsSettingItem[] = [];

  original.forEach((originalItem, index) => {
    const modifiedItem = modified[index];

    // 对比每个字段，如果字段发生变化，记录这个对象
    if (!isEqual(originalItem, modifiedItem)) {
      changedItems.push(modifiedItem); // 保存修改后的数据
    }
  });

  return changedItems;
};

const handleChange = (item: GameLeftMo) => {
  currentData.value = item;
};

const getData = async (item: GameLeftMo) => {
  try {
    state.loading = true;
    const res = await reqGameOddsShow(item.LotteryId);
    state.list = cloneDeep(Object.values(res.data));
    state.defaultList = cloneDeep(Object.values(res.data));
    state.minLimit = Math.max(...state.list.map(item => item.MinPersonl));
    state.maxLimit = Math.max(...state.list.map(item => item.MaxMaxPreBet));
    state.persionMaxLimit = Math.max(...state.list.map(item => item.MaxMaxSingleBitch));
    state.allLimit = Math.max(...state.list.map(item => item.MaxMaxBitch));
    state.loading = false;
  } catch (error) {
    state.loading = false;
    console.log(error);
  }
};

// 保存修改的全部
const handleSaveAll = (flag: boolean = false) => {
  ElMessageBox.confirm(`是否进行【全部修改】操作`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          const list = getChangedItems(state.defaultList, state.list);
          console.log(list);
          await reqGameOddsEdit({
            ...(flag ? { ChangeSameCategory: 1 } : {}),
            LotteryId: currentData.value?.LotteryId,
            List: flag ? [] : list
          });
          message.success("修改成功");
          state.all = null;
          state.min = null;
          state.max = null;
          state.persionMax = null;
          instance.confirmButtonLoading = false;
          getData(currentData.value!);
          done(); // 操作成功后关闭对话框
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};
const handleMaster = (e: any) => {
  console.log(e);
};
watch(
  () => currentData.value,
  val => {
    state.all = null;
    state.min = null;
    state.max = null;
    state.persionMax = null;
    getData(val!);
  }
);

watch(
  () => state.min,
  val => {
    if (val) {
      state.list.forEach(item => {
        item.RoomSingleMinLimit = val;
      });
    } else {
      state.list = cloneDeep(state.defaultList);
    }
  }
);
watch(
  () => state.max,
  val => {
    if (val) {
      state.list.forEach(item => {
        item.RoomSingleMaxLimit = val;
      });
    } else {
      state.list = cloneDeep(state.defaultList);
    }
  }
);
watch(
  () => state.persionMax,
  val => {
    if (val) {
      state.list.forEach(item => {
        item.MaxLimitPersonBet = val;
      });
    } else {
      state.list = cloneDeep(state.defaultList);
    }
  }
);
watch(
  () => state.all,
  val => {
    if (val) {
      state.list.forEach(item => {
        item.RoomAllLimit = val;
      });
    } else {
      state.list = cloneDeep(state.defaultList);
    }
  }
);
</script>
<style lang="scss" scoped>
:deep() {
  .el-input,
  .el-textarea {
    --el-input-bg-color: #f9f9f9;
  }
}
</style>
